/**
 * 用户权限校验
 */

'use strict';

var Promise = require('bluebird');
var _ = require('lodash');
var request = require('request');
var UserModel = require('../models/user');

var global = require('../global');
var Utils = require('../helper/utils');

module.exports = {

  /**
   * 是否登录
   * @param req
   * @returns {boolean}
   */
  isLogin: function (req) {
    return req.session.user ? true : false;
  },

  /**
   * 是否是管理员
   * @param req
   * @returns {*|boolean}
   */
  isMaster: function (req) {
    return res.session.user && req.session.user.role === 1;
  },

  /**
   * 是否已经激活
   * @param req
   * @returns {*|boolean}
   */
  isActive: function (req) {
    return req.session.user && req.session.user.status === 1;
  },

  /**
   * 登录提交
   * @param req
   * @param res
   * @param next
   */
  loginPost: function(options) {
    return new Promise(function(resolve, reject){
      if(options.user_email === global.email && options.user_password === global.password){
        var doc = {
          user_nickname : 'adminstrator',
          user_email: global.email,
          user_role : 1,
          user_status : 1
        };
        resolve(doc);
      }else{
        UserModel.findOne({user_email: options.user_email}, function(err, doc){
          if( err ) { return reject('数据库错误') };
          if( doc === null) { return reject('该用户不存在') };
          var encryptPwd = Utils.md5(options.user_password+global.salt);
          if(encryptPwd === doc.user_password){
            doc.user_password = '';
            resolve(doc);
          }else{
            reject('密码错误');
          };
        })
      }

    })
  }

}